// pages/toolPages/md5/md5.js
let interstitialAd = null;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        currentVidUrl: "",
        downloadVidUrl: "",
        rowVidMd5: "",
        newVidMd5: "",
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
      if(wx.createInterstitialAd){
        interstitialAd = wx.createInterstitialAd({ adUnitId: 'adunit-c04c8689d165224f' })
        interstitialAd.onLoad(() => {
          console.log('onLoad event emit')
        })
        interstitialAd.onError((err) => {
          console.log('onError event emit', err)
        })
        interstitialAd.onClose((res) => {
          console.log('onClose event emit', res)
        })
      }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        // 超过70秒可以显示插屏广告
        var currentTime = new Date();
        var lastTime = wx.getStorageSync('cpShowTime')
        var interval = (currentTime.getTime() -lastTime.getTime()) /1000;
        console.log("==间隔： "+interval)
        if (interval>70){
          wx.setStorageSync('cpShowTime', currentTime)
          interstitialAd.show().catch((err) => {
            console.error(err)
            wx.setStorageSync('cpShowTime', lastTime)
          })
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    upLoadVid: function(){
        var ts = this;
        ts.setData({currentVidUrl: "",
                    downloadVidUrl: "",
                    rowVidMd5: "",
                    newVidMd5: "",})
        wx.chooseMedia({
            count: 1,
            mediaType: ['video'],
            sourceType: ['album'],
            sizeType:['original'],
            maxDuration: 30,
            camera: 'back',
            success(res) {
                ts.setData({
                    currentVidUrl: res.tempFiles[0].tempFilePath,
                });
                ts.getVidMd5(res.tempFiles[0].tempFilePath, "rowVidMd5");
            },
            fail(res){
                wx.showModal({
                  title: '上传失败',
                  content: '请重新上传，如持续不能上传，请至用户页联系客服',
                  complete: (res) => {
                    if (res.cancel) {
                    }
                    if (res.confirm) {
                    }
                  }
                })
            },
        })
    },
    modifyVid: function(){
        var ts = this;
        wx.getVideoInfo({
          src: ts.data.currentVidUrl,
          success(res){
              wx.showLoading({
                title: '正在修改MD5',
              })
              wx.compressVideo({
                bitrate: res.bitrate-1,
                fps: res.fps,
                resolution: 1,
                src: ts.data.currentVidUrl,
                success(res){
                    wx.hideLoading();
                    ts.setData({downloadVidUrl: res.tempFilePath})
                    ts.getVidMd5(res.tempFilePath, "newVidMd5");
                },
                fail(res){
                    wx.hideLoading();
                    wx.showModal({
                      title: '修改失败',
                      content: '请重试，多次失败请联系客服',
                      complete: (res) => {
                        if (res.cancel) {
                        }
                        if (res.confirm) {
                        }
                      }
                    })
                },
              })
          },
          fail(res){
          }
        })
    },

    modifyVidFast: function(){
        var ts = this;
        wx.getVideoInfo({
            src: ts.data.currentVidUrl,
            success(res){
                console.log(res)
                wx.showLoading({
                    title: '正在修改MD5',
                  })
                const ab2 = new ArrayBuffer((res.size+1)*1024)
                const fs2 = wx.getFileSystemManager()
                fs2.open({
                    filePath: ts.data.currentVidUrl,
                    flag: 'r',
                    success(res) {
                      // 读取文件到 ArrayBuffer 中
                      console.log('openFile')
                      console.log(res)
                      fs2.read({
                        fd: res.fd,
                        arrayBuffer: ab2,
                        length: ab2.byteLength,
                        success(res) {
                        //   res.arrayBuffer.slice(2,res.bytesRead+2);
                        var filePath = `${wx.env.USER_DATA_PATH}/tempvideo.mp4`;
                        console.log(filePath)
                          fs2.writeFile({
                            filePath: filePath,
                            data: res.arrayBuffer.slice(0,res.bytesRead+2),
                            encoding: 'binary',
                            success(res) {
                                wx.hideLoading();
                                ts.setData({downloadVidUrl: filePath})
                                ts.getVidMd5(filePath, "newVidMd5");
                            },
                            fail(res) {
                                 wx.hideLoading();
                                wx.showModal({
                                  title: '修改失败',
                                  content: '超快修改失败，请重试或联系客服',
                                  complete: (res) => {
                                    if (res.cancel) {
                                      
                                    }
                                
                                    if (res.confirm) {
                                      
                                    }
                                  }
                                })
                            },
                          })
                        },
                        fail(res){
                            wx.hideLoading();
                        }
                      })
                    },
                    fail(res){
                        wx.hideLoading();
                    }
                  })
            }
        })
    },

    downloadVid: function(){
        var ts = this;
        if (ts.data.downloadVidUrl == ""){
            console.log("downloadVidUrl is null;")
            return
        }else{
            console.log(ts.data.downloadVidUrl)
            wx.showLoading({
              title: "正在下载",
            })
            wx.saveVideoToPhotosAlbum({
                filePath: ts.data.downloadVidUrl,
                success(res){
                    wx.hideLoading()
                    wx.showToast({
                      title: '视频下载成功',
                      icon: 'success',
                      duration: 2500,
                    })
                },
                fail(res){
                    wx.hideLoading()
                    console.log(res.errMsg)
                    wx.showModal({
                      title: '下载失败请重试',
                      content: res.errMsg,
                      complete: (res) => {
                        if (res.cancel) {
                          
                        }
                    
                        if (res.confirm) {
                          wx.showModal({
                            title: 'res',
                            content: res,
                            complete: (res) => {
                              if (res.cancel) {
                                
                              }
                          
                              if (res.confirm) {
                                
                              }
                            }
                          })
                        }
                      }
                    })
                }
              })
        }
    },

    getVidMd5: function(filePath, param){
        wx.showLoading({
          title: '正在计算MD5',
        })
        const fs = wx.getFileSystemManager()
        var ts = this;
        wx.getVideoInfo({
          src: filePath,
          success(res){
                const ab = new ArrayBuffer((res.size+1)*1024)
                fs.open({
                    filePath: filePath,
                    flag: 'r',
                    success(res) {
                      // 读取文件到 ArrayBuffer 中
                      console.log('openFile')
                      console.log(res)
                      fs.read({
                        fd: res.fd,
                        arrayBuffer: ab,
                        length: ab.byteLength,
                        success(res) {
                          var MD5 = require('../../../utils/md5.js');
                          let spark = new MD5.ArrayBuffer();
                          spark.append(res.arrayBuffer.slice(0,res.bytesRead));
                          var md5String = spark.end(false);
                          ts.changeData(param, md5String);
                          wx.hideLoading()
                        },
                        fail(res){
                            wx.hideLoading()
                            console.log(res);
                            ts.changeData(param, "视频过大，计算失败，但已经修改")
                        }
                      })
                    },
                    fail(res){
                        wx.hideLoading()
                        console.log(res)
                        ts.changeData(param, "视频过大，计算失败，但已经修改")
                    }
                  })
          },
          fail(res){
                wx.hideLoading()
              console.log(res);
              ts.changeData(param, "视频过大，计算失败，但已经修改")
          },
        })
    },
    
    changeData: function(param1, param2){
        var ts = this;
        if (param1 === "rowVidMd5"){
            ts.setData({rowVidMd5: param2})
        }
        if (param1 === "newVidMd5"){
            ts.setData({newVidMd5: param2})
        }
    },
    adLoadB() {
      console.log('MD5页面底部小程序视频广告加载成功')
    },
    adErrorB(err) {
      console.log('MD5页面底部小程序视频广告加载失败', err)
    },
    adCloseB() {
      console.log('MD5页面底部小程序视频广告关闭')
    },
})